//
//  XZMessageConsultVC.m
//  Teecloud
//
//  Created by PC on 2018/11/5.
//  Copyright © 2018年 小志. All rights reserved.
//

#import "XZMessageConsultVC.h"
#import "XZMemberMsg.h"
#import "XZMemberCheckMsg.h"
#import "XZMemberData.h"
#import "XZMsgTypeList.h"
#import "LrdSuperMenu.h"
#import "GMVoiceListModel.h"
#import "XZMemberCheckMsgCell.h"
@interface XZMessageConsultVC ()<UITableViewDelegate,UITableViewDataSource, LrdSuperMenuDataSource, LrdSuperMenuDelegate>
@property (nonatomic, strong) XZMemberMsg *msgModel;
@property (nonatomic, assign) NSInteger pageIndex;
@property (nonatomic, strong) NSMutableArray *dataSource;
@property (nonatomic, strong) UITableView *tableView;
@property (nonatomic, strong) LrdSuperMenu *menu;
//保证下拉菜单只刷新一次
@property (nonatomic, assign) BOOL isSuccess;
@property (nonatomic, strong) NSArray *timeSource;
//全部组员的userId
@property (nonatomic, copy) NSString *userId;
//全部类别
@property (nonatomic, assign) NSInteger ChatType;
//日期
@property (nonatomic, copy) NSString *queryStartDate;
@end
#define Identifier @"MemberCheckMsgCell"
@implementation XZMessageConsultVC
- (void)viewDidLoad {
    [super viewDidLoad];
    self.title = @"消息查询";
    self.view.backgroundColor = kWhiteColor;
    [self getQueryMemberMsg];
}
#pragma mark - MJRefresh
- (void)getQueryMemberMsg{
    self.pageIndex = 0;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    //没有全部组员
    if (!self.model.IsManageRole) {
        [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"memberUserId"];
    }else{
         [dict setValue:self.userId forKey:@"memberUserId"];
    }
    //msgTypeCode:消息类别代码（选项值为0）
    [dict setValue:@(self.ChatType) forKey:@"msgTypeCode"];
    //查询开始日期
    [dict setValue:self.queryStartDate forKey:@"queryStartDate"];
    
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=QueryMemberMsg&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [weakself.tableView.mj_header endRefreshing];
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                [weakself.dataSource removeAllObjects];
                XZMemberMsg * model = [XZMemberMsg mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                weakself.msgModel = model;
                [weakself.dataSource addObjectsFromArray:model.MsgList];
                [weakself.tableView.mj_footer endRefreshing];
                [weakself.tableView.mj_header endRefreshing];
                if (weakself.dataSource.count == 0) {
                    [weakself.tableView setupEmptyDataText:@"暂无数据" secoundText:@"" buttonTit:@"" verticalOffset:0 emptyImage:NODATAIMG tapBlock:^{
                        
                    } butClick:^{
                        
                    }];
                }
                [weakself.tableView reloadData];
                //保证下拉菜单只刷新一次
                if (!weakself.isSuccess) {
                   [weakself.menu reloadData];
                    weakself.isSuccess = YES;
                }
            }else{
                [weakself.tableView.mj_footer endRefreshing];
                [weakself.tableView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.tableView.mj_footer endRefreshing];
            [weakself.tableView.mj_header endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
- (void)getMoreQueryMemberMsg{
    self.pageIndex ++;
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:self.groupId forKey:@"groupId"];
    [dict setValue:@(self.pageIndex) forKey:@"pageIndex"];
    //没有全部组员
    if (!self.model.IsManageRole) {
        [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"memberUserId"];
    }else{
        [dict setValue:self.userId forKey:@"memberUserId"];
    }
    //msgTypeCode:消息类别代码（选项值为0）
    [dict setValue:@(self.ChatType) forKey:@"msgTypeCode"];
    //查询开始日期
    [dict setValue:self.queryStartDate forKey:@"queryStartDate"];
    
    kWeakObject(self)
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=QueryMemberMsg&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                XZMemberMsg * model = [XZMemberMsg mj_objectWithKeyValues:[responseObject objectForKey:RESULT_NAME_Data]];
                [weakself.dataSource addObjectsFromArray:model.MsgList];
                if (model.MsgList.count >0) {
                    [weakself.tableView.mj_footer endRefreshing];
                    [weakself.tableView.mj_header endRefreshing];
                    [weakself.tableView reloadData];
                }else{//没有数据的时候就显示暂无数据
                    weakself.tableView.mj_footer.state = MJRefreshStateNoMoreData;
                }
            }else{
                [weakself.tableView.mj_footer endRefreshing];
                [weakself.tableView.mj_header endRefreshing];
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [weakself.tableView.mj_footer endRefreshing];
            [weakself.tableView.mj_header endRefreshing];
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
#pragma mark - LrdSuperMenuDataSource
- (NSInteger)numberOfColumnsInMenu:(LrdSuperMenu *)menu {
    if (!self.model.IsManageRole) {
        return 2;
    }
    return 3;
}
- (NSInteger)menu:(LrdSuperMenu *)menu numberOfRowsInColumn:(NSInteger)column {
    if (!self.model.IsManageRole) {//没有全部组员项
        if (column == 0) {
            return self.msgModel.MsgTypeList.count;
        }else{
            return self.timeSource.count;
        }
    }else{
        if (column == 0) {
            return self.msgModel.MsgTypeList.count;
        }else if (column == 1){
            return self.msgModel.MemberList.count;
        }else{
            return self.timeSource.count;
        }
    }
}

- (NSString *)menu:(LrdSuperMenu *)menu titleForRowAtIndexPath:(LrdIndexPath *)indexPath{
    if (!self.model.IsManageRole) {//没有全部组员项
        if (indexPath.column == 0) {
            XZMsgTypeList *model = self.msgModel.MsgTypeList[indexPath.row];
            return model.Name;
        }else{
            return self.timeSource[indexPath.row];
        }
    }else{
        if (indexPath.column == 0) {
            XZMsgTypeList *model = self.msgModel.MsgTypeList[indexPath.row];
            return model.Name;
        }else if (indexPath.column == 1){
            XZMemberData *model = self.msgModel.MemberList[indexPath.row];
            return model.Name;
        }else{
            return self.timeSource[indexPath.row];
        }
    }
}
#pragma mark - LrdSuperMenuDelegate
- (void)menu:(LrdSuperMenu *)menu didSelectRowAtIndexPath:(LrdIndexPath *)indexPath{
    if (!self.model.IsManageRole) {//没有全部组员项
        if (indexPath.column == 0) {
            XZMsgTypeList *model = self.msgModel.MsgTypeList[indexPath.row];
            self.ChatType = model.ChatType;
        }else{
            //最近三月（选项值为空）其他的以今天为基准倒推 格式2018-11-20
            NSString *timeStr =  self.timeSource[indexPath.row];
            if ([timeStr isEqualToString:@"最近三月"]) {
                self.queryStartDate = nil;
            }else if ([timeStr isEqualToString:@"最近一月"]){
                self.queryStartDate = [self getBeforeYear:0 month:-1 day:0];
            }else if ([timeStr isEqualToString:@"最近十天"]){
                self.queryStartDate = [self getBeforeYear:0 month:0 day:-10];
            }else if ([timeStr isEqualToString:@"最近三天"]){
                self.queryStartDate = [self getBeforeYear:0 month:0 day:-3];
            }else if ([timeStr isEqualToString:@"今天"]){
                self.queryStartDate = [self getCurrentTime];
            }
        }
    }else{
        if (indexPath.column == 0) {
            XZMsgTypeList *model = self.msgModel.MsgTypeList[indexPath.row];
            self.ChatType = model.ChatType;
        }else if (indexPath.column == 1){
            XZMemberData *model = self.msgModel.MemberList[indexPath.row];
            if ([model.Name isEqualToString:@"全部组员"]) {
                //全部组员”（选项值为空）
                self.userId = nil;
            }else{
                self.userId = model.UserId;
            }
        }else{//日期
            //最近三月（选项值为空）其他的以今天为基准倒推 格式2018-11-20
            NSString *timeStr =  self.timeSource[indexPath.row];
            if ([timeStr isEqualToString:@"最近三月"]) {
                self.queryStartDate = nil;
            }else if ([timeStr isEqualToString:@"最近一月"]){
                self.queryStartDate = [self getBeforeYear:0 month:-1 day:0];
            }else if ([timeStr isEqualToString:@"最近十天"]){
                self.queryStartDate = [self getBeforeYear:0 month:0 day:-10];
            }else if ([timeStr isEqualToString:@"最近三天"]){
                self.queryStartDate = [self getBeforeYear:0 month:0 day:-3];
            }else if ([timeStr isEqualToString:@"今天"]){
                self.queryStartDate = [self getCurrentTime];
            }
        }
    }
    [self getQueryMemberMsg];
}
#pragma mark - TableViewDataSource
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    self.tableView.mj_footer.hidden = self.dataSource.count > 0? NO:YES;
    return self.dataSource.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    kWeakObject(self)
    XZMemberCheckMsg *model = self.dataSource[indexPath.row];
    XZMemberCheckMsgCell *memberCheckMsgCell = [tableView dequeueReusableCellWithIdentifier:Identifier];
    memberCheckMsgCell.model = model;
    memberCheckMsgCell.indexPath = indexPath;
    memberCheckMsgCell.parentController = self;
    //点赞
    memberCheckMsgCell.likeBlock = ^(XZMemberCheckMsg * _Nonnull model, NSIndexPath * _Nonnull indexPath) {
        [weakself likeContent:model refreshIndexPath:indexPath];
    };
    memberCheckMsgCell.hasReadBlock = ^(NSInteger index, NSString * _Nonnull voiceID, NSString * _Nonnull voiceStr) {
        NSDictionary *dict= @{@"from":FROM_IOS,
                              @"busiOrgId":[XGMArchiverTools cacheForKey:BUSIORGID],
                              @"loginFinger":[XGMArchiverTools cacheForKey:USER_identifierNumber],
                              @"userId":[XGMArchiverTools cacheForKey:USER_UserId],
                              @"voiceId":voiceID,
                              };
        [MBProgressHUD showHUDAddedTo:weakself.view animated:YES];
        [HJNetwork HTTPWithMethod:HJRequestMethodPOST url:[NSString stringWithFormat:@"v30.teecloud.cn/ajax-api.ashx?$c=TeeyunApp&$m=PostVoiceReadStatus&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
            [MBProgressHUD hideHUDForView:weakself.view animated:YES];
            if (!error) {
                if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                    if ([voiceStr isEqualToString:@"MSG"]) {
                        //MsgBody.VoiceList
                        for (NSInteger i=0; i<model.MsgBody.VoiceList.count; i++) {
                            GMVoiceListModel *temModel = model.MsgBody.VoiceList[i];
                            if (i == index) {
                                temModel.IsReaded =YES;
                            }
                        }
                    }else{
                        //Quote.VoiceList
                        for (NSInteger i=0; i<model.Quote.VoiceList.count; i++) {
                            GMVoiceListModel *temModel = model.Quote.VoiceList[i];
                            if (i == index) {
                                temModel.IsReaded =YES;
                            }
                        }
                    }
                    [weakself.tableView reloadData];
                }else{
                    [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
                }
            }else{
                [MBProgressHUD showErrorOrSuc:@"请求出错" toView:weakself.view];
            }
        }];
    };
    return memberCheckMsgCell;
}
#pragma mark - TableViewDelegate
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    XZMemberCheckMsg *model = self.dataSource[indexPath.row];
    return model.cellHeight;
}
- (void)likeContent:(XZMemberCheckMsg *)model refreshIndexPath:(NSIndexPath *)indexPath{
    NSMutableDictionary *dict = [NSMutableDictionary dictionary];
    [dict setValue:FROM_IOS forKey:@"from"];
    [dict setValue:[XGMArchiverTools cacheForKey:BUSIORGID] forKey:@"busiOrgId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_UserId] forKey:@"userId"];
    [dict setValue:[XGMArchiverTools cacheForKey:USER_identifierNumber] forKey:@"loginFinger"];
    [dict setValue:@(2) forKey:@"type"];
    [dict setValue:model.MsgBody.Id forKey:@"recId"];
    if (!model.MsgBody.IsLike) {
        [dict setValue:@(1) forKey:@"op"];//点赞
    }else{
        [dict setValue:@(2) forKey:@"op"];//取消点赞
    }
    kWeakObject(self)
    [MBProgressHUD showHUDAddedTo:self.view animated:YES];
    [HJNetwork POSTWithURL:[NSString stringWithFormat:@"ajax-api.ashx?$c=TeeyunApp&$m=LikeOrUnlike&$v=%@",VERSION] parameters:dict cachePolicy:HJCachePolicyIgnoreCache callback:^(id responseObject, NSError *error) {
        [MBProgressHUD hideHUDForView:weakself.view animated:YES];
        if (!error) {
            if ([[responseObject objectForKey:RESULT_NAME_Success] boolValue]) {
                NSString *msg =[responseObject objectForKey:RESULT_NAME_Message];
                if (msg != nil) {
                    [MBProgressHUD showErrorOrSuc:msg toView:weakself.view];
                }
                XZMemberCheckMsg *model = self.dataSource[indexPath.row];
                model.MsgBody.IsLike = !model.MsgBody.IsLike;
                NSInteger likeCount ;
                if (model.MsgBody.IsLike) {
                    likeCount = [model.MsgBody.LikeCount integerValue] + 1;
                }else{
                    likeCount = [model.MsgBody.LikeCount integerValue] - 1;
                }
                model.MsgBody.LikeCount = @(likeCount);
                //将之前的模型给替换
                [self.dataSource replaceObjectAtIndex:indexPath.row withObject:model];
                [self.tableView reloadRowsAtIndexPaths:[NSArray arrayWithObjects:indexPath, nil] withRowAnimation:UITableViewRowAnimationNone];
            }else{
                [MBProgressHUD showErrorOrSuc:[responseObject objectForKey:RESULT_NAME_Message] toView:weakself.view];
            }
        }else{
            [MBProgressHUD showErrorOrSuc:@"网络异常" toView:weakself.view];
        }
    }];
}
#pragma mark - Setter
- (NSMutableArray *)dataSource{
    if (!_dataSource) {
        _dataSource = [[NSMutableArray alloc]init];
    }
    return _dataSource;
}
- (NSArray *)timeSource{
    if (!_timeSource) {
        _timeSource= @[@"最近三月", @"最近一月", @"最近十天", @"最近三天", @"今天"];
    }
    return _timeSource;
}
- (LrdSuperMenu *)menu{
    if (!_menu) {
        _menu = [[LrdSuperMenu alloc] initWithOrigin:CGPointMake(0, 0) andHeight:44];
        _menu.backgroundColor = kWhiteColor;
        _menu.delegate = self;
        _menu.dataSource = self;
        [self.view addSubview:_menu];
    }
    return _menu;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 44, DEVICE_WIDTH, DEVICE_HEIGHT-kBottomSafeHeight-kNavBarAndStatusBarHeight-44) style:UITableViewStylePlain];
        _tableView.delegate = self;
        _tableView.dataSource = self;
        _tableView.showsVerticalScrollIndicator =false;
        _tableView.separatorStyle =UITableViewCellSeparatorStyleNone;
        //注册
        [_tableView registerNib:[UINib nibWithNibName:@"XZMemberCheckMsgCell" bundle:nil] forCellReuseIdentifier:Identifier];
        //上下拉刷新
        _tableView.mj_header = [MJRefreshNormalHeader headerWithRefreshingTarget:self refreshingAction:@selector(getQueryMemberMsg)];
        _tableView.mj_footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(getMoreQueryMemberMsg)];
        _tableView.mj_footer.hidden =YES;
        [self.view addSubview:_tableView];
    }
    return _tableView;
}

/**
 获取当前日期的后面日期

 @param year 年
 @param month 月
 @param day 日
 @return 日期
 */
- (NSString *)getBeforeYear:(NSInteger)year month:(NSInteger)month day:(NSInteger)day{
    //得到当前的时间
    NSDate * mydate = [NSDate date];
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSCalendar *calendar = [[NSCalendar alloc] initWithCalendarIdentifier:NSCalendarIdentifierGregorian];
    NSDateComponents *comps = nil;
    comps = [calendar components:NSCalendarUnitYear|NSCalendarUnitMonth|NSCalendarUnitMonth fromDate:mydate];
    NSDateComponents *adcomps = [[NSDateComponents alloc] init];
    [adcomps setYear:year];
    [adcomps setMonth:month];
    [adcomps setDay:day];
    NSDate *newdate = [calendar dateByAddingComponents:adcomps toDate:mydate options:0];
    NSString *beforDate = [dateFormatter stringFromDate:newdate];
    return beforDate;
}

/**
 获取当前的日期

 @return 日期字符串
 */
- (NSString *)getCurrentTime{
    NSDateFormatter * dateFormatter = [[NSDateFormatter alloc] init];
    [dateFormatter setDateFormat:@"yyyy-MM-dd"];
    NSString *currentDate = [dateFormatter stringFromDate:[NSDate date]];
    return currentDate;
}
@end

